package config

import (
	"fmt"
	"github.com/go-kit/kit/log"
	"github.com/openzipkin/zipkin-go"
	zipkinhttp "github.com/openzipkin/zipkin-go/reporter/http"
	"github.com/spf13/viper"
	"test2/pkg/bootstrap"
	conf "test2/pkg/config"

	"os"
)

var Logger log.Logger
var ZipkinTracer *zipkin.Tracer

func init() {
	Logger = log.NewLogfmtLogger(os.Stderr)
	Logger = log.With(Logger, "ts", log.DefaultTimestampUTC)
	Logger = log.With(Logger, "caller", log.DefaultCaller)
	conf.InitConfig()
	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf("err:%s\n", err)
	}
	if err := conf.SubParse("mysql", &conf.MysqlConfig); err != nil {
		Logger.Log("Fail to parse mysql", err)
	}

	if err := conf.SubParse("zipkintrace", &conf.TraceConfig); err != nil {
		Logger.Log("Fail to parse trace", err)
	}
	ZipkinURL := "http://" + conf.TraceConfig.Host + ":" + conf.TraceConfig.Port + conf.TraceConfig.Url
	fmt.Println("ZipkinUrl:", ZipkinURL)

	//fmt.Println("----discoberCongig.serviceName:", bootstrap.DiscoverConfig.ServiceName)
	var err error
	var useNoopTracer bool
	useNoopTracer = ZipkinURL == ""
	var reporter = zipkinhttp.NewReporter(ZipkinURL)
	zEP, _ := zipkin.NewEndpoint(bootstrap.DiscoverConfig.ServiceName, bootstrap.HttpConfig.Host+":"+bootstrap.HttpConfig.Port)
	ZipkinTracer, err = zipkin.NewTracer(
		reporter, zipkin.WithLocalEndpoint(zEP), zipkin.WithNoopTracer(useNoopTracer),
	)
	if err != nil {
		Logger.Log("err", err)
		os.Exit(1)
	}
	if !useNoopTracer {
		Logger.Log("use NoopTracer :", ZipkinURL)
	}
}
